package com.sanda.androidcourse.chapter07;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.sanda.androidcourse.R;

public class BroadCastActivity extends AppCompatActivity {

    private MyBroadcastReceiver receiver;
    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_broad_cast);

        // 创建广播接收器实例
        receiver = new MyBroadcastReceiver();

        // 创建IntentFilter，定义需要接收的广播类型
        IntentFilter filter = new IntentFilter("com.sanda.androidcourse.MY_NOTIFICATION");
        // 动态注册广播接收器（API 26+，需要传入 receiverExported）
        registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED);

        Button btnSendBroadcast = findViewById(R.id.btnSendBroadcast);
        btnSendBroadcast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 创建Intent并发送广播
                Intent intent = new Intent("com.sanda.androidcourse.MY_NOTIFICATION");
                intent.putExtra("message", "Hello from BroadCastActivity!");
                sendBroadcast(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播接收器，防止内存泄漏
        unregisterReceiver(receiver);
    }
}